<template>
  <div id="testPaper">
    <Breadcrumb content="考试管理" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="40">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getTestPaperList" @search-click="getTestPaperList"></vxe-input>
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="getTestPaperList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="add()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="testPaperBox">
            <vxe-table ref="testPaperTableRef" :loading="showLoading" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="testPaperList" :row-config="{ isCurrent: true, isHover: true }" @current-change="currentChangeEvent" resizable show-overflow>
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column field="testCode" title="试卷编码"></vxe-column>
              <vxe-column field="testTitle" title="试卷标题"></vxe-column>
              <vxe-column field="startDate" title="开始时间"></vxe-column>
              <vxe-column field="endDate" title="结束时间"> </vxe-column>
              <vxe-column field="totalScore" title="总分" width="40"> </vxe-column>
              <vxe-column field="duration" title="考试时长" width="60"> </vxe-column>
              <vxe-column field="seq" title="顺序" width="30"> </vxe-column>
              <vxe-column field="paperType" title="考试类型">
                <template #default="{ row }">
                  {{ formatterPaperType(row.paperType) }}
                </template>
              </vxe-column>
              <vxe-column field="status" title="状态">
                <template #default="{ row }">
                  <el-tag size="small"> {{ formatterType(row.status) }}</el-tag>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="60">
          <el-tabs type="border-card">
            <el-tab-pane label="基本信息">
              <el-scrollbar style="height: 100%">
                <el-form ref="testPaperFormRef" :model="testPaperForm" :rules="baseFormRules" label-width="100px" class="form-input-m" v-loading="showBaseFormLoading" inline-message>
                  <el-scrollbar style="height: 100%">
                    <el-form-item label="编码" prop="testCode">
                      <el-input v-model="testPaperForm.testCode" placeholder="编码" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="试卷标题" prop="testTitle"> <el-input v-model="testPaperForm.testTitle" placeholder="试卷标题" clearable></el-input> </el-form-item>
                    <el-form-item label="开始时间" prop="startDate">
                      <el-date-picker v-model="testPaperForm.startDate" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="开始时间" clearable />
                    </el-form-item>
                    <el-form-item label="考试结束时间" prop="endDate">
                      <el-date-picker v-model="testPaperForm.endDate" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="培训结束时间" clearable />
                    </el-form-item>
                    <el-form-item label="总分" prop="totalScore"> <el-input v-model="testPaperForm.totalScore" placeholder="总分" clearable></el-input> </el-form-item>
                    <el-form-item label="考试类型" prop="paperType">
                      <el-select v-model="testPaperForm.paperType" placeholder="考试类型" style="width: 200px">
                        <el-option v-for="item in paperTypeOptions" :key="item.value" :label="item.name" :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="考试时长" prop="duration"> <el-input v-model="testPaperForm.duration" placeholder="考试时长" clearable></el-input> </el-form-item>
                    <el-form-item label="顺序" prop="seq">
                      <el-input-number v-model="testPaperForm.seq" :min="1" :max="1000" />
                    </el-form-item>
                    <el-form-item label="考试人" prop="sysUserList">
                      <el-select v-model="testPaperForm.sysUserList" value-key="id" multiple placeholder="考试人" style="margin-right: 10px">
                        <el-option v-for="item in userOptions" :key="item.id" :label="item.realname" :value="item" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="备注" prop="remake">
                      <el-input v-model="testPaperForm.remake" :rows="6" type="textarea" placeholder="备注" clearable style="margin-right: 10px"></el-input>
                    </el-form-item>
                    <el-form-item class="form-footer">
                      <template #default>
                        <el-button type="primary" v-loading="saveLoading" @click="save()">暂存</el-button>
                        <el-button type="primary" v-loading="saveBigLoading" @click="updateStatus(1)">开始考试</el-button>
                        <el-button type="default" @click="add()">重置</el-button>
                      </template>
                    </el-form-item>
                  </el-scrollbar>
                </el-form>
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane label="题目维护"><TestPaperManager ref="TestPaperManagerRef"></TestPaperManager> </el-tab-pane>
            <el-tab-pane label="试卷预览"><TestPaperView ref="TestPaperViewRef"></TestPaperView> </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { isEmpty } from 'lodash';
import TestPaperManager from './TestPaperManager.vue'; //题目维护
import TestPaperView from './TestPaperView.vue'; //试卷预览

let { proxy }: any = getCurrentInstance();
//根据关键字搜索
let searchForm = reactive({
  searchValue: '',
  year: null
});
let showLoading = ref(false); //左侧试卷表格加载状态
const testPaperList = reactive([]); //左侧试卷表格数据

let showBaseFormLoading = ref(false); //右侧基本信息表单加载状态

//右侧基本信息表单数据
const testPaperForm = reactive({
  id: '',
  testCode: '',
  testTitle: '',
  startDate: '',
  endDate: '',
  totalScore: '',
  paperType: '',
  status: 0,
  seq: 0,
  sysUserList: [],
  remake: ''
});

// 右侧基本信息表单校验规则
let baseFormRules: any = {
  testCode: [{ required: true, message: '请输入编码' }],
  testTitle: [{ required: true, message: '请输入试卷标题' }],
  // startDate: [{ required: true, message: '请选择开始时间' }],
  // endDate: [{ required: true, message: '请选择考试结束时间' }],
  totalScore: [{ required: true, message: '请设置总分' }],
  status: [{ required: true, message: '请选择状态' }],
  duration: [{ required: true, message: '请设置考试时长' }],
  seq: [{ required: true, message: '请设置排序' }],
  sysUserList: [{ required: true, message: '请选择考试人' }]
};

//右侧基本信息——试卷状态下拉选项
const typeOptions = reactive([
  {
    name: '未开始',
    value: 0
  },
  {
    name: '进行中',
    value: 1
  },
  {
    name: '已结束',
    value: 2
  }
]);

// 考试类型
const paperTypeOptions = reactive([
  {
    name: '试剂考试',
    value: 0
  },
  {
    name: '体检考试',
    value: 1
  },
  {
    name: '检验考试',
    value: 2
  }
]);
const userOptions = reactive([]); //右侧基本信息——考试人集合
let saveLoading = ref(false); //保存
let TestPaperManagerRef: any = ref(null); //题目维护ref标记
let TestPaperViewRef: any = ref(null); //试卷预览ref标记

// 方法定义区 =============================================================
onMounted(() => {
  getUserList();
  getTestPaperList();
});

// 获取右侧考试人员列表
function getUserList() {
  userOptions.length = 0;
  const url = '/api/user/getUserInfoList';
  proxy.$http
    .get(url, {})
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        userOptions.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 获取左侧试卷表格列表信息
function getTestPaperList() {
  showLoading.value = true;
  testPaperList.length = 0;
  const url = '/wk/test/paper/getTestPaperList';
  proxy.$http
    .get(url, { params: { keyWord: searchForm.searchValue } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        testPaperList.push(...res.data);
        currentChangeEvent({ row: testPaperList[0] });
        const $xTable = proxy.$refs.testPaperTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(testPaperList[0]);
        }
        showLoading.value = false;
      }
    })
    .catch((err: any) => {
      showLoading.value = false;
      proxy.$alert(err, '提示');
    });
}
// 左侧试卷表格行点击事件
function currentChangeEvent(row: any) {
  Object.assign(testPaperForm, row.row);
  TestPaperManagerRef.value.getBigSubjects(row.row);
  TestPaperViewRef.value.getPaperView(row.row);
}

// 添加
function add() {
  const el: any = proxy.$refs.testPaperFormRef;
  el.resetFields(); //重置该表单项，将其值重置为初始值，并移除校验结果
  Object.keys(testPaperForm).forEach((key) => {
    switch (typeof testPaperForm[key]) {
      case 'string':
        testPaperForm[key] = '';
        break;
      case 'number':
        testPaperForm[key] = 0;
        break;
    }
    if (key === 'seq') {
      testPaperForm[key] = testPaperList.length + 1;
    }
    if (Array.isArray(testPaperForm[key])) {
      testPaperForm[key].length = 0;
    }
  });
  testPaperForm.status = 0;
}
// 保存
function save() {
  let url = '';
  if (testPaperForm.id == '' || testPaperForm.id == null || testPaperForm.id == undefined) {
    url = '/wk/test/paper/addTestPaper';
  } else {
    url = '/wk/test/paper/editTestPaper';
  }
  const el: any = proxy.$refs.testPaperFormRef;
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    proxy.$http
      .post(url, testPaperForm)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        getTestPaperList();
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  });
}

// 开始考试
function updateStatus(status: number) {
  testPaperForm.status = status;
  save();
}

// 删除
function handleDelete() {
  const $xTable = proxy.$refs.testPaperTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/test/paper/deleteTestPaper';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              getTestPaperList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}
// 格式化左侧试卷表格状态
function formatterType(cellValue) {
  const item = typeOptions.find((item) => item.value === cellValue);
  return item ? item.name : '';
}

// 格式化左侧试卷表格状态
function formatterPaperType(cellValue) {
  const item = paperTypeOptions.find((item) => item.value === cellValue);
  return item ? item.name : '';
}
</script>

<style lang="scss" scoped>
#testPaper {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .testPaperBox {
        height: calc(100% - 40px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          padding: 0;
          height: calc(100% - 39px);
          .el-tab-pane {
            height: 100%;
          }
          //基本信息表单
          #pane-0 {
            padding: 15px;
            height: calc(100% - 30px);
          }
          // 题目维护
          #pane-1 {
            padding: 0 20px;
          }
          // 试卷预览
          #pane-2 {
            padding: 20px 0;
            height: calc(100% - 40px);
          }
        }
      }
    }
  }
}
</style>
